<template>
  <el-card>
    <h2>订单管理</h2>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="订单数据统计" name="stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card>订单总数：{{ stats.totalCount }}</el-card>
          </el-col>
          <el-col :span="6">
            <el-card>订单总金额：¥{{ stats.totalAmount?.toFixed(2) }}</el-card>
          </el-col>
          <el-col :span="12">
            <el-card>
              <div ref="statusPie" style="height:300px;"></div>
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="mt-4">
          <el-col :span="24">
            <el-card>
              <div ref="trendChart" style="height:350px;"></div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="统计查询" name="query">
        <!-- 查询表单+表格 -->
        <el-form :inline="true" class="mb-2">
          <el-form-item label="订单号">
            <el-input v-model="queryParam.orderSn" placeholder="请输入订单号" clearable />
          </el-form-item>
          <el-button type="primary" @click="loadOrders">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form>
        <el-table :data="orders" v-loading="loading" border>
          <el-table-column prop="orderId" label="订单ID" width="100" />
          <el-table-column prop="orderSn" label="订单编号" min-width="160" />
          <el-table-column prop="userId" label="用户ID" width="100" />
          <el-table-column prop="totalAmount" label="订单总额" width="120">
            <template #default="scope">
              ¥{{ scope.row.totalAmount?.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120">
            <template #default="scope">
              <el-tag :type="statusTagType(scope.row.status)">
                {{ statusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="paymentMethod" label="支付方式" width="120" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column prop="updateTime" label="更新时间" width="180" />
        </el-table>
        <div class="mt-4 flex justify-end">
          <el-pagination
            v-model:current-page="queryParam.current"
            v-model:page-size="queryParam.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="loadOrders"
            @current-change="loadOrders"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>
<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

const activeTab = ref('stats')

const queryParam = ref({
  current: 1,
  size: 10,
  orderSn: null
})
const orders = ref([])
const total = ref(0)
const loading = ref(false)

const stats = ref({ totalCount: 0, totalAmount: 0, statusMap: {}, trend: [] })
const statusPie = ref(null)
const trendChart = ref(null)
let statusPieChart = null
let trendChartInstance = null

const loadOrders = async () => {
  loading.value = true
  try {
    const res = await axios.post('/api/orders/orders/findOrders', queryParam.value)
    orders.value = res.data.data.records
    total.value = res.data.data.total
  } catch (e) {
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

const resetQuery = () => {
  queryParam.value = {
    current: 1,
    size: 10,
    orderSn: null
  }
  loadOrders()
}

const statusText = (status) => {
  switch(status) {
    case 0: return '未付款'
    case 1: return '已付款'
    case 2: return '已发货'
    case 3: return '已完成'
    case 4: return '已取消'
    default: return '未知'
  }
}
const statusTagType = (status) => {
  switch(status) {
    case 0: return 'info'
    case 1: return 'success'
    case 2: return 'warning'
    case 3: return 'primary'
    case 4: return 'danger'
    default: return ''
  }
}

const fetchStats = async () => {
  try {
    const res = await axios.get('/api/orders/orders/stats')
    stats.value = res.data.data
    await nextTick()
    renderStatusPie()
    renderTrendChart()
  } catch (e) {
    ElMessage.error('获取订单统计失败')
  }
}

const renderStatusPie = () => {
  if (!statusPie.value) return
  if (!statusPieChart) {
    statusPieChart = echarts.init(statusPie.value)
  }
  const statusLabels = ['未付款', '已付款', '已发货', '已完成', '已取消']
  const statusData = Object.entries(stats.value.statusMap || {}).map(([k, v]) => ({
    name: statusLabels[k] || k,
    value: v
  }))
  statusPieChart.setOption({
    title: { text: '订单状态分布', left: 'center' },
    tooltip: { trigger: 'item' },
    legend: { bottom: 0 },
    series: [{
      name: '订单状态',
      type: 'pie',
      radius: '60%',
      data: statusData
    }]
  })
}

const renderTrendChart = () => {
  if (!trendChart.value) return
  if (!trendChartInstance) {
    trendChartInstance = echarts.init(trendChart.value)
  }
  const xData = (stats.value.trend || []).map(item => item.date)
  const yData = (stats.value.trend || []).map(item => item.count)
  trendChartInstance.setOption({
    title: { text: '近7天订单数量趋势', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: xData },
    yAxis: { type: 'value' },
    series: [{
      name: '订单数',
      type: 'line',
      data: yData
    }]
  })
}

watch(activeTab, (val) => {
  if (val === 'stats') {
    fetchStats()
  }
})

onMounted(() => {
  if (activeTab.value === 'stats') fetchStats()
  loadOrders()
})
</script>

<style scoped>
.mb-2 {
  margin-bottom: 0.5rem;
}
.mt-4 {
  margin-top: 1rem;
}
</style>